<script setup lang="ts">
  import { onMounted, onUnmounted } from 'vue'
  import AMapLoader from '@amap/amap-jsapi-loader'
  import { useAmapStore } from '@/store/amap'
  import { storeToRefs } from 'pinia'

  const amapStore = useAmapStore()
  const { amap, amapInstance } = storeToRefs(amapStore)

  // 地图初始化
  const initMap = () => {
    AMapLoader.load({
      key: import.meta.env.VITE_AMAP_KEY, //需要设置您申请的key
      version: '2.0',
      plugins: ['AMap.ToolBar', 'AMap.Driving'],
      AMapUI: {
        version: '1.1',
        plugins: [],
      },
      Loca: {
        version: '2.0.0',
      },
    })
      .then((AMap) => {
        amapInstance.value = AMap
        amap.value = new AMap.Map('amap-container', {
          viewMode: '2D',
          zoom: 8.2, // 初始缩放级别
          zooms: [2, 22], // 缩放级别范围
          center: [120.294222, 29.356357],
          layers: [
            new AMap.createDefaultLayer({
              zooms: [3, 20], //可见级别
              visible: true, //是否可见
              opacity: 1, //透明度
              zIndex: 0, //叠加层级
            }),
          ],
        })
        // 去除道路
        if (amap.value) {
          // @ts-ignore
          amap.value.setFeatures(['bg', 'building', 'point'])
        }
      })
      .catch(() => {})
  }
  onMounted(() => {
    initMap()
  })

  onUnmounted(() => {
    if (amap.value) {
      // @ts-ignore
      amap.value.destroy()
    }
  })
</script>

<template>
  <div id="amap-container"></div>
</template>

<style scoped lang="less">
  #amap-container {
    width: 100%;
    height: 100%;
  }
</style>
